
#include "main.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int i=0, j=0;
float real_value = 0.0;   // real temperature value
float temp_value = 0.0;
float temp_buf = 0.0;
int t2_set = 0;
float d1;
int d2;
char *str, str8[8];
float kalman_now = 0.0;
float kalman_last = 0.0;

int show_value = 0;   // showing value of temperature
int avg_value = 0;    // average value
bool lock = FALSE;
bool real_lock = FALSE;

void interrupt2(void)
{
	i++;
	
	// Refresh the temperature in 1 second

	if (i==999) {
		i=0;

#ifdef USE_DS18B20
		ds18b20_start();
		temp_buf = ds18b20_read_temp()*0.625;   //读取温度数值;
		kalman_now = temp_buf;
#else
		temp_value = get_temp();
		// 温度误差校准
		if (offset_positive)
			real_value = temp_value*10 + temp_offset;
		else
			real_value = temp_value*10 - temp_offset;
		// 数据校准
		temp_buf = adjust(real_value);
		kalman_now = kalmanFilter(temp_buf);
#endif

		d1 = show_value - temp_set;
		d2 = temp_buf - temp_set;

		// 加热PWM控制
		t2_set = temp_pwm*10 + PIDCalc(&sPID, temp_buf);

		if (temp_set>600)
			t2_set += (temp_set-600);

		if (d2<0) {
			if (temp_set<=TEMP_LIMITED) {
				GPIO_WriteLow(HEAT_PORT, HEAT);
				GPIO_WriteLow(LED_PORT, LED_STATUS);
			}
		}else{
			GPIO_WriteHigh(HEAT_PORT, HEAT);
			GPIO_WriteHigh(LED_PORT, LED_STATUS);
		}

		show_value = kalman_now;

		if (real_lock) {
			show_value = temp_set;
		}else{
			show_value = kalman_now;
		}

		if ((show_value-temp_set)>=0) {
			if (show_value>=800)
				lock = TRUE;
			else if ((show_value-temp_set)>0)
				lock = TRUE;
		}

		if (ABS(kalman_now-temp_set)>temp_lock) {
			lock = FALSE;
			real_lock = FALSE;
		}

		if (lock) {
			if (ABS(show_value-temp_set)<1) {
				real_lock = TRUE;
			}		
		}

		// 温度报警
		if ((show_value)>=(temp_set+temp_alert)) {
			GPIO_WriteLow(LED_PORT, LED_POWER);
		}else{
			GPIO_WriteHigh(LED_PORT, LED_POWER);
		}

		kalman_last = kalman_now;
	}

	if (i==t2_set) {
		GPIO_WriteHigh(HEAT_PORT, HEAT);
		GPIO_WriteHigh(LED_PORT, LED_STATUS);
	}
	
	TIM2_ClearITPendingBit(TIM2_IT_UPDATE); //清中断标志位

}
